package com.dsl.tms.service;

import com.dsl.tms.annotation.LoginRequired;
import com.dsl.tms.entity.db.Message;
import com.dsl.tms.entity.db.MessageTrash;
import com.dsl.tms.entity.redis.AdminRedis;
import com.dsl.tms.entity.response.*;
import com.dsl.tms.entity.result.Result;
import com.dsl.tms.enums.MessageResult;
import com.dsl.tms.model.MessageModel;
import com.dsl.tms.repository.MessageRepository;
import com.dsl.tms.repository.MessageTrashRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.transaction.Transactional;
import java.sql.Date;


@Service
public class MessageService {

    @Autowired
    private MessageRepository messageDao;

    @Autowired
    private MessageTrashRepository messageTrashDao;

    @Autowired
    private RedisTemplate redisTemplate;


    private static Logger LOGGER = LoggerFactory.getLogger(MessageService.class);

    @LoginRequired
    public MessageInitMap init(String token){
        MessageInitMap messageInitMap = new MessageInitMap();
        AdminRedis adminRedis = (AdminRedis) redisTemplate.opsForValue().get(token);
        messageInitMap.setReaded(MessageModel.getMessageList(messageDao.findReadedList(adminRedis.getUserId())));
        messageInitMap.setUnread(MessageModel.getMessageList(messageDao.findUnreadList(adminRedis.getUserId())));
        messageInitMap.setTrash(MessageModel.getMessageList(messageDao.findTrashList(adminRedis.getUserId())));
        Result result = new Result();
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        messageInitMap.setResult(result);
        return messageInitMap;
    }

    @LoginRequired
    public UnReadCountMap count(String token){
        UnReadCountMap unReadCountMap = new UnReadCountMap();
        Result result = new Result();
        AdminRedis adminRedis = (AdminRedis) redisTemplate.opsForValue().get(token);
        int towho = adminRedis.getUserId();
        Integer count = messageDao.countAllByTowhoAndReaded(towho,0) == null? 0 : messageDao.countAllByTowhoAndReaded(towho,0);
        unReadCountMap.setCount(count);
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        unReadCountMap.setResult(result);
        return unReadCountMap;
    }

    @LoginRequired
    public ContentMap getContentByMsgId(Integer message_id,String token){
        ContentMap contentMap = new ContentMap();
        Result result = new Result();
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        String content = messageDao.findContentById(message_id).get(0).toString() ;
        if (content == null || content.isEmpty()){
            content = messageTrashDao.findContentByMessage_id(message_id);
        }
        contentMap.setContent(content);
        contentMap.setResult(result);
        return contentMap;
    }

    @LoginRequired
    @Transactional
    public HasReadMap has_read(int message_id,String token){
        HasReadMap hasReadMap = new HasReadMap();
        Result result = new Result();
        try{
            messageDao.hasRead(message_id);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            hasReadMap.setHas_read(false);
            result.setCode(MessageResult.FAIL.getCode());
            result.setDescription(MessageResult.FAIL.getDescription()+" :"+e.getMessage());
            hasReadMap.setResult(result);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return hasReadMap;
        }
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        hasReadMap.setHas_read(true);
        hasReadMap.setResult(result);
        return hasReadMap;
    }


    @LoginRequired
    @Transactional
    public RemoveReadedMap remove_readed(int message_id,String token){
        RemoveReadedMap removeReadedMap = new RemoveReadedMap();
        Result result = new Result();
        try{
            Message message = messageDao.getOne(message_id);
            MessageTrash messageTrash = new MessageTrash();
            messageTrash.setMessage_id(message.getId());
            messageTrash.setTitle(message.getTitle());
            messageTrash.setContent(message.getContent());
            messageTrash.setAdddate(message.getAdddate());
            messageTrash.setEditdate(message.getEditdate());
            messageTrash.setTowho(message.getTowho());
            messageTrash.setReaded(message.getReaded());
            messageTrash.setTrashdate(new Date(new java.util.Date().getTime()));
            messageTrashDao.save(messageTrash);
            messageDao.delete(message_id);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            removeReadedMap.setRemove_readed(false);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setCode(MessageResult.FAIL.getCode());
            result.setDescription(MessageResult.FAIL.getDescription()+": "+e.getMessage());
            removeReadedMap.setResult(result);
            return removeReadedMap;
        }
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        removeReadedMap.setRemove_readed(true);
        removeReadedMap.setResult(result);
        return removeReadedMap;
    }

    @LoginRequired
    @Transactional
    public RestoreMap restore(int message_id,String token){
        RestoreMap restoreMap = new RestoreMap();
        Result result = new Result();
        try{
            MessageTrash messageTrash = messageTrashDao.findMessageTrashByMessage_id(message_id);
            Message message = new Message();
            message.setId(messageTrash.getMessage_id());
            message.setTitle(messageTrash.getTitle());
            message.setContent(messageTrash.getContent());
            message.setAdddate(messageTrash.getAdddate());
            message.setEditdate(messageTrash.getEditdate());
            message.setTowho(messageTrash.getTowho());
            message.setReaded(messageTrash.getReaded());
            messageDao.save(message);
            messageTrashDao.deleteByMessage_id(message_id);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setCode(MessageResult.FAIL.getCode());
            result.setDescription(MessageResult.FAIL.getDescription()+": "+e.getMessage());
            restoreMap.setRestore(false);
            restoreMap.setResult(result);
        }
        result.setCode(MessageResult.SECCESS.getCode());
        result.setDescription(MessageResult.SECCESS.getDescription());
        restoreMap.setRestore(true);
        restoreMap.setResult(result);
        return restoreMap;
    }



}
